﻿using System;
using System.Collections.Generic;

namespace RG.Common
{
    public class LazyCache<K,V> : Dictionary<K,V>
    {
        readonly Func<K, V> loader;

        public LazyCache(Func<K,V> _loader)
        {
            loader = _loader;
        }

        public new V this[K key]
        {
            get { return Get(key); }
        }

        V Get(K key)
        {
            V value;
            if (TryGetValue(key, out value)) return value;
            value = loader(key);
            Add(key, value);
            return value;
        }
    }
}
